// src/components/core/CheckBox.tsx
import React, { FC, useEffect } from 'react'
import { List, Typography, Checkbox as AntdCheckbox } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { getCategory } from '../../store/actions/category.action'
import { AppState } from '../../store/reducers'
import { CategoryState } from '../../store/reducers/category.reducer'
import { CheckboxValueType } from 'antd/lib/checkbox/Group'

const { Title } = Typography

interface Props {
    handleFilter: (arg: string[]) => void
}

const CheckBox: FC<Props> = ({ handleFilter }) => {
    const dispatch = useDispatch()

    // 获取分类列表
    const category = useSelector<AppState, CategoryState>(state => state.category)

    useEffect(() => {
        dispatch(getCategory())
    }, [])

    // 多选框改变时获取当前的数组 id，修改筛选条件
    const onChange = (checkedValue: CheckboxValueType[]) => {
        // checkedValue 所选分类的 _id 数组
        handleFilter(checkedValue as string[])
    }
    return (
    <>
        <Title level={4}>按照分类筛选</Title>
        <AntdCheckbox.Group 
            className="checkBoxFilter"
            options={
                // 将数据改造
                category.category.result.map(item => ({ 
                    label: item.name, 
                    value: item._id 
                }))
            }
            onChange={onChange}
         />
        
    </>
    )
}

export default CheckBox